
package com.scalar.chiptrack.operations.process.actions;

import java.util.ArrayList;
import java.util.HashMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.scalar.ScalarException;
import com.scalar.chiptrack.ChipTrackAction;
import com.scalar.chiptrack.commons.SessionKeys;
import com.scalar.chiptrack.db.DBTransaction;
import com.scalar.chiptrack.operations.process.ProcessStep;
import com.scalar.chiptrack.operations.process.Upload;
import com.scalar.chiptrack.operations.process.VendorLocation;
import com.scalar.chiptrack.operations.process.dao.FabDAO;
import com.scalar.chiptrack.operations.process.dao.PCMDataDAO;
import com.scalar.chiptrack.operations.process.dao.ProcessTrackDAO;
import com.scalar.chiptrack.operations.process.dao.ProductDao;
import com.scalar.chiptrack.operations.process.dao.VendorLocationDAO;
import com.scalar.chiptrack.operations.process.forms.FabForm;
import com.scalar.chiptrack.operations.process.forms.FabProcessRecipeForm;
import com.scalar.chiptrack.operations.process.forms.FabRecipeForm;
import com.scalar.chiptrack.operations.vendor.dao.VendorDAO;
import com.scalar.chiptrack.users.User;

public final class FabAction extends ChipTrackAction 
{
	public ActionForward execute (ActionMapping mapping, 
								  ActionForm form, 
								  HttpServletRequest request, 
								  HttpServletResponse response) throws Exception 
	{
		String STEP_TYPE = "FAB";
		HttpSession ses = request.getSession(true);
		String fabName = "";
		String trackId = "";
		ArrayList vendorLocationList = new ArrayList();
		HashMap errors = new HashMap();
		User user = (User)ses.getAttribute (SessionKeys.USER_KEY);
		if (user == null)
		{
			return (mapping.findForward ("login"));
		}	 
		if(request.getParameter("action")==null)
		{
			FabForm fabForm = null;
			//FabDAO fabDao = new FabDAO();
			String processStepId=(String)request.getParameter("processStepID");

			if(processStepId!=null)
			{
				fabForm = FabDAO.loadFabProcessData(processStepId);
				fabForm.setProcessStepId(processStepId);
				vendorLocationList = VendorDAO.getFabLocations (Integer.parseInt(processStepId));
				ses.setAttribute("productId",ProductDao.getParentProductId(processStepId));
			}
			else 
			{
				fabName = (String)request.getParameter( "fabName" );
				trackId = (String)request.getParameter( "trackID" );
		
				fabForm = new FabForm();	
				fabForm.setProcessStepId( "-1" );
				fabForm.setFabName(fabName);
				//fabForm.setDupFabName(new String[0]);
				ses.setAttribute( "productId" , request.getParameter("productID") );
				ses.setAttribute( "trackId" , trackId );
				vendorLocationList = VendorDAO.getFabLocations();
				/*ArrayList fabLocationList= VendorDAO.getFabLocations();
				VendorLocation vendorLocation = null;
	
				Location loc=null;
				if( fabLocationList == null )
				{
					fabLocationList = new ArrayList(0);
				}
					
				for( int i=0; i < fabLocationList.size(); i++ )
				{					
					vendorLocation = ( VendorLocation ) fabLocationList.get(i);
					vendorLocation.setLocationID( vendorLocation.getLocationID() );
					vendorLocation.setLocationName( vendorLocation.getLocationName() );
					vendorLocationList.add( vendorLocation );				
				}*/
			}
			request.setAttribute( "vendorLocations" , vendorLocationList );
			request.setAttribute( "fabForm" , fabForm );
			return ( mapping.findForward("success") );  
		}
		else
		{
			DBTransaction dbTransaction = null;
			boolean success = false;
			int processStepId=0;
			FabDAO fabDao = null;

			try 
			{
				try
				{
					dbTransaction = DBTransaction.getInstance();
					dbTransaction.begin();		
				}
				catch (Throwable t)
				{
					t.printStackTrace();
				}
				FabForm fabForm = (FabForm) form;
				int productId = new Integer((String)ses.getAttribute("productId")).intValue();
				ProcessStep processSetUp = null;
				processStepId = Integer.parseInt(fabForm.getProcessStepId());
				Upload upLoad = null;
				int procedureDocId=0;
				int maskDocId=0;
				FabRecipeForm fabRecipeForm = (FabRecipeForm)ses.getAttribute("recipe");
				ArrayList recipeList = new ArrayList();

				if(fabRecipeForm!=null)
				{
					String parameter[]=fabRecipeForm.getParameter();
					String maxValue[] =fabRecipeForm.getMaxValue();
					String minValue[] =fabRecipeForm.getMinValue();
			  
					for(int i=0; i<parameter.length;i++)
					{
						if(!parameter[i].equals(""))
						{
							FabProcessRecipeForm fabProcessRecipeForm = new FabProcessRecipeForm();
							fabProcessRecipeForm.setParameter(parameter[i]);
							fabProcessRecipeForm.setMaxValue(maxValue[i]);
							fabProcessRecipeForm.setMinValue(minValue[i]);
							recipeList.add(fabProcessRecipeForm);
						}
					}
				}
				//PCMDataDAO pcmData = null;
				//ProductDao productDao = new ProductDao();
				fabDao = new FabDAO();
				VendorLocation vendorLocation = null;
				//VendorLocationDAO vendorLocationDAO = null; 

				int [] locationID		= fabForm.getLocationID();
				int [] priority			= fabForm.getPriority();
				String [] locationName	= fabForm.getLocationName();
				int [] split			= fabForm.getSplit();
				int [] capacityWeek		= fabForm.getCapacityWeek();
				float [] normalCost		= fabForm.getNormalCost();
				float [] expressCost	= fabForm.getExpressCost();
				int [] normalCycleTime	= fabForm.getNormalCycleTime();
				int [] expressCycleTime	= fabForm.getExpressCycleTime();
				float [] expectedYieid  = fabForm.getExpectedYield();

                String check="";
				
				for(int i=0;i<locationName.length;i++)
				{
				   check=request.getParameter("checkLoc"+i);	
					if(check!=null)
					{
						vendorLocation=new VendorLocation();
						vendorLocation.setLocationID(locationID[i]+"");
						vendorLocation.setPriority(priority[i]+"");
						vendorLocation.setLocationName(locationName[i]);
						vendorLocation.setSplit(split[i]+"");
						vendorLocation.setCapacityWeek(capacityWeek[i]+"");
						vendorLocation.setNormalCost(normalCost[i]);
						vendorLocation.setExpressCost(expressCost[i]);
						vendorLocation.setNormalCycleTime(normalCycleTime[i]+"");
						vendorLocation.setExpressCycleTime(expressCycleTime[i]+"");
						vendorLocation.setExpectedYield(expectedYieid[i]);
						vendorLocationList.add(vendorLocation);	
					}
				}

				String[] partNumbers = new String[fabForm.getDupProductName().length+1];
				partNumbers[0] = fabForm.getFabName();
				for(int i=0; i < fabForm.getDupProductName().length ; i++)
				{
					partNumbers[i+1] = fabForm.getDupProductName()[i];
				}
				// added by ravikanth on 16 Sep 2003 
				// check for duplicates in Product_Map_Table
				String dupNames = ProductDao.checkDupInProductMapTable(partNumbers,processStepId,STEP_TYPE);
				if( dupNames.length() > 0 )
				{
					errors.put ("Part Numbers Already exists ", dupNames );
                    vendorLocationList = getAllFabVendorLocations(fabForm,request);
                    if(vendorLocationList == null){
                        if(processStepId!=-1)
                        {
                            vendorLocationList = VendorDAO.getFabLocations (processStepId);
                        }
                        else
                        {
                            vendorLocationList = VendorDAO.getFabLocations();
                        }
                    }
					request.setAttribute (SessionKeys.ERROR_MESSAGES, errors);
					request.setAttribute( "fabForm" , fabForm );
					request.setAttribute( "vendorLocations" , vendorLocationList );
					return ( mapping.findForward("success") );
				}

				if(processStepId== -1)
				{
					//Step 1: Save Process Step table
					processStepId=ProcessStep.getProcessStepID(dbTransaction,"FAB","FAB",fabForm.getComments());
					//Step 2: Save Product table
					ProductDao.saveProcessStepProduct(dbTransaction,processStepId,fabForm.getFabName(),productId);
					//Step 3: Save Procedure Doc File 
					if(fabForm.getProcDocNo()!=null && fabForm.getProcDocFile()!=null)
						procedureDocId = Upload.getProcedureDocID(dbTransaction,"FAB",fabForm.getProcDocNo(),fabForm.getProcDocFile());
					//Step:4 Save Mask Doc File	
					if(fabForm.getMaskIdNo()!=null && fabForm.getMaskIdFile()!=null)
						maskDocId = Upload.getMaskDocID(dbTransaction,"FAB",fabForm.getMaskIdNo(),fabForm.getMaskIdFile());
					//Step:5 Save PCM Data						
					PCMDataDAO.savePCMData(dbTransaction,processStepId,recipeList.iterator());
					//Step:6 Save VendorLocations
					VendorLocationDAO.saveVendorLocations(dbTransaction,processStepId, vendorLocationList.iterator());
					//Step:7 Save Fab Table
					fabDao.saveFab(dbTransaction,processStepId,fabForm.getLotHoldYieldLimit(),fabForm.getStandardUnitCost(),fabForm.getGross(),fabForm.getPoFrequency(),fabForm.getLotScrapYieldLimit(),fabForm.getTargetYield(),procedureDocId,maskDocId);
					trackId =(String)ses.getAttribute("trackId");
					
					// added by RaviKanth to set duplicate names to fab partnumber
					//Step:8 To save to Product_Map_Table
					if( fabForm.getDupProductName()!= null && fabForm.getDupProductName().length > 0 )
					{
						ProductDao.saveProductMap( dbTransaction , processStepId , fabForm.getDupProductName() , vendorLocationList );
					}
					
					//Step:9 Update Fab Track Table
					ProcessTrackDAO.updateFabTrack(dbTransaction,processStepId,Integer.parseInt(trackId)) ;
                    
					request.setAttribute("baseProductID", productId+"");
					success = true;
				}
				// Updating Fab 
				else
				{
					//Step 1: Update Process Step Table	
					ProcessStep.updateProcessStepID(dbTransaction,"FAB","FAB",fabForm.getComments(),processStepId);
					//Step 2: Update fab part number 	
					ProductDao.updateProcessStepProduct(dbTransaction,processStepId,fabForm.getFabName(),productId);
					//Step 3: Save Procedure Doc File(Insert new record even though it exists) 
					if(fabForm.getProcDocNo()!=null && fabForm.getProcDocFile()!=null)
						procedureDocId = Upload.getProcedureDocID(dbTransaction,"FAB",fabForm.getProcDocNo(),fabForm.getProcDocFile());
					//Step:4 Save Mask Doc File	
					if(fabForm.getMaskIdNo()!=null && fabForm.getMaskIdFile()!=null)
						maskDocId = Upload.getMaskDocID(dbTransaction,"FAB",fabForm.getMaskIdNo(),fabForm.getMaskIdFile());
					//Step:5 Delete PCM Data and insert new PCM Data
					PCMDataDAO.deletePCMData(dbTransaction,processStepId);
					PCMDataDAO.savePCMData(dbTransaction,processStepId,recipeList.iterator());
					//Step:6 Delete Vendor Locations and insert vendorLocations
					VendorLocationDAO.deleteVendorLocations(dbTransaction,processStepId);
					VendorLocationDAO.saveVendorLocations(dbTransaction,processStepId, vendorLocationList.iterator());
					//Step:7 Update Fab Data
					fabDao.updateFab(dbTransaction,processStepId,fabForm.getLotHoldYieldLimit(),fabForm.getStandardUnitCost(),fabForm.getGross(),fabForm.getPoFrequency(),fabForm.getLotScrapYieldLimit(),fabForm.getTargetYield(),procedureDocId,maskDocId);
					
					// added by RaviKanth to set duplicate names to fab partnumber
					//Step:8 To save to Product_Map_Table
					if( fabForm.getDupProductName()!= null && fabForm.getDupProductName().length > 0 )
					{
						ProductDao.saveProductMap( dbTransaction , processStepId , fabForm.getDupProductName() , vendorLocationList );
					}						 
					
					success = true;
					request.setAttribute("baseProductID",new Integer(productId).toString());
				}	
			}
			catch (ScalarException se) 
			{
				// Exception while inserting fab
				// log it
				se.printStackTrace();
			}
			finally 
			{
				// Rollback or Commit the Transaction
				if (success == true) {
					dbTransaction.commit();
				}
				else {
					dbTransaction.rollback();
				}
			}

			ses.setAttribute("processStepId",new Integer(processStepId));
			ses.removeAttribute("recipe");
			ses.removeAttribute("vendorLocations");
			request.setAttribute("fabStageList",FabDAO.getFabStage(processStepId));
			return (mapping.findForward("skipfab")); 
		}
	}

    private ArrayList getAllFabVendorLocations (FabForm fabForm,HttpServletRequest request){

            ArrayList VendorLocationList = new ArrayList();

            VendorLocation vendorLocation = null;
			int [] locationID		= fabForm.getLocationID();
			int [] priority			= fabForm.getPriority();
			String [] locationName	= fabForm.getLocationName();
			int [] split			= fabForm.getSplit();
			int [] capacityWeek		= fabForm.getCapacityWeek();
			float [] normalCost		= fabForm.getNormalCost();
			float [] expressCost	= fabForm.getExpressCost();
			int [] normalCycleTime	= fabForm.getNormalCycleTime();
			int [] expressCycleTime	= fabForm.getExpressCycleTime();
			float [] expectedYieid  = fabForm.getExpectedYield();

            String check="";

    		for(int i=0;i<locationName.length;i++)
	    	{
                vendorLocation=new VendorLocation();
                vendorLocation.setLocationID(locationID[i]+"");
                vendorLocation.setPriority(priority[i]+"");
                vendorLocation.setLocationName(locationName[i]);
                vendorLocation.setSplit(split[i]+"");
                vendorLocation.setCapacityWeek(capacityWeek[i]+"");
                vendorLocation.setNormalCost(normalCost[i]);
                vendorLocation.setExpressCost(expressCost[i]);
                vendorLocation.setNormalCycleTime(normalCycleTime[i]+"");
                vendorLocation.setExpressCycleTime(expressCycleTime[i]+"");
                vendorLocation.setExpectedYield(expectedYieid[i]);
                check=request.getParameter("checkLoc"+i);
                if(check!=null){
                    vendorLocation.setSelect("on");
                }
                VendorLocationList.add(vendorLocation);

		}
        return VendorLocationList;
    }
}